#include"Socket.hpp"
#include"Common.hpp"
#include"Potorol.hpp"
#include<iostream>
#include<string>
#include<memory>

using namespace MySocket;

void Usage(const std::string &proc)
{
    std::cout<<"Usage: "<<proc<<" server_ip server_port"<<std::endl;
}

void GetDataFromStdin(int *x,int *y,char *oper)
{
    std::cout<<"X: ";
    std::cin>>*x;
    std::cout<<"Y: ";
    std::cin>>*y;
    std::cout<<"Oper: ";
    std::cin>>*oper;
}

int main(int argc,char* argv[])
{
    if(argc!=3)
    {
        Usage(argv[0]);
        exit(USAGE_ERROR);
    }

    std::string serip = argv[1];
    uint16_t serport = std::stoi(argv[2]);

    std::shared_ptr<Socket> client = std::make_shared<TcpSocket>();
    client->BuildSocket();
    if(client->Connect(serip,serport)!=0)
    {
        std::cerr<<"connect error"<<std::endl;
        exit(CONNECT_ERROR);
    }

    std::unique_ptr<Potorol> protocol = std::make_unique<Potorol>();
    std::string buffer;
    while(true)
    {
        int x,y;
        char oper;
        GetDataFromStdin(&x,&y,&oper);

        std::string req_str = protocol->BuildRequestString(x,y,oper);

        client->Send(req_str);

        Response resp;
        bool res = protocol->GetResponse(client,buffer,resp);
        if(!res)
            break;

        resp.ShowResult();
    }
    return 0;
}